'''
Script for add header to a files in a directory.
Usage:
	python headerize.py DIR HEADER
Example:
	python headerize.py ./src header.txt
Notes:
	- directory path could be relative or absolute.
	- permissions is not checked
'''

from optparse import OptionParser

import os
from os.path import join as filejoin

def main():
	'''
	Parse command line args options and evaulate.
	Return options dictionary.
	'''
	usage = "usage %prog -d DIR -f HEADER"
	parser = OptionParser(usage)
	parser.add_option('-d', '--directory', dest="dirname",
			help="directory with .py file to change")
	
	parser.add_option('-f', '--header-file', dest="header",
			help="file with header to add")
	
	(options, args) = parser.parse_args()

	if (not options.dirname) and (not options.header):
		parser.error("incorrect number of argument.\nTry headerize.py -h")
	else:
		
		return options

def loadheader(filename):
	'''
	Open header file and returns a string.
	'''
	FILE = open(filename)
	return FILE.read()

def getfiles(dirname):
	'''
	Return a list of all files in a directory and in all subdirectory.
	'''
	allfiles = []
	for root, dirs, files in os.walk(dirname):
		#files = filter(lambda x: x[-3:]==".py", files)
		#files = map(lambda f:join(root, f), files)
		files = [filejoin(root,f) for f in files if f[-3:]=='.py']
		allfiles.extend(files)
	return allfiles

def addheader(_file, string):
	'''
	Add string as header of file
	'''
	FILE = open(_file, 'r+')
	body = FILE.read()
	strings = "\n".join(["'''", string, "'''", body])
	FILE.seek(0)
	FILE.writelines(strings)
	FILE.close()
	print "File {0} is been modified".format(_file)


if __name__ == "__main__":
	options = main()
	header = loadheader(options.header)
	files = getfiles(options.dirname)
	for _file in files:
		addheader(_file, header)
